import { observable, action, computed, runInAction } from 'mobx';
import { projectApi } from '../../../services/projectApi';
import dayjs from 'dayjs';
import LRUCache from 'lru-cache';

// 项目列表缓存
const projectCache = new LRUCache({
  max: 100,          // 最多缓存100个项目
  maxAge: 1000 * 60 * 10  // 缓存10分钟
});

class ProjectListStore {
  // 状态定义
  @observable loading = false;
  @observable projects = [];
  @observable quickAccessList = [];
  @observable filter = {
    search: '',
    status: 'all',
    cate: 0,
    devManager: 0,
    bizManager: 0,
    sortType: 'time'
  };
  
  @observable pagination = {
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true
  };

  // 计算属性
  @computed get filteredProjects() {
    return this.projects.filter(project => {
      // 搜索筛选
      if (this.filter.search && !project.model?.includes(this.filter.search)) {
        return false;
      }
      
      // 状态筛选
      if (this.filter.status !== 'all' && project.status !== this.filter.status) {
        return false;
      }
      
      // 类型筛选
      if (this.filter.cate !== 0 && project.projectType !== this.filter.cate) {
        return false;
      }
      
      // 研发负责人筛选
      if (this.filter.devManager !== 0 && project.developmentManager !== this.filter.devManager) {
        return false;
      }
      
      // 业务负责人筛选
      if (this.filter.bizManager !== 0 && project.businessManager !== this.filter.bizManager) {
        return false;
      }
      
      return true;
    });
  }
  
  @computed get projectCount() {
    return this.projects.length;
  }

  // 行为方法
  @action
  async loadProjects(isRefresh = false) {
    if (isRefresh) {
      this.pagination.page = 1;
      this.projects = [];
    }
    
    this.loading = true;
    try {
      const result = await projectApi.getProjects({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        ...this.filter
      });
      
      runInAction(() => {
        const newProjects = result.list.map(item => ({
          ...item,
          startDateFormatted: dayjs(item.startDate).format('YYYY-MM-DD'),
          endDateFormatted: dayjs(item.endDate).format('YYYY-MM-DD'),
          deadlineFormatted: dayjs(item.deadline).format('YYYY-MM-DD'),
          deadlineStatus: this._getDeadlineStatus(item.deadline),
          deadlineMessage: this._getDeadlineMessage(item.deadline),
          statusText: this._getStatusText(item.status),
          statusColor: this._getStatusColor(item.status),
          progressColor: this._getProgressColor(item.completionPercentage)
        }));
        
        this.projects = isRefresh ? newProjects : [...this.projects, ...newProjects];
        this.pagination.total = result.total;
        this.pagination.hasMore = this.projects.length < result.total;
        this.loading = false;
      });
    } catch (error) {
      runInAction(() => {
        this.loading = false;
      });
      wx.showToast({
        title: '加载项目失败: ' + error.message,
        icon: 'none'
      });
    }
  }
  
  @action
  setFilter(filter) {
    this.filter = {
      ...this.filter,
      ...filter
    };
  }
  
  @action
  async loadQuickAccessList() {
    try {
      const result = await projectApi.getQuickAccessProjects();
      runInAction(() => {
        this.quickAccessList = result;
      });
    } catch (error) {
      console.error('加载快速访问列表失败:', error);
    }
  }
  
  @action
  async addToQuickAccess(project) {
    try {
      await projectApi.addQuickAccessProject(project._id);
      await this.loadQuickAccessList();
      wx.showToast({
        title: '已添加到快速访问',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: '添加失败: ' + error.message,
        icon: 'none'
      });
    }
  }
  
  @action
  async removeFromQuickAccess(projectId) {
    try {
      await projectApi.removeQuickAccessProject(projectId);
      await this.loadQuickAccessList();
      wx.showToast({
        title: '已从快速访问移除',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: '移除失败: ' + error.message,
        icon: 'none'
      });
    }
  }
  
  // 工具方法
  _getDeadlineStatus(deadline) {
    const now = dayjs();
    const deadlineDate = dayjs(deadline);
    
    if (deadlineDate.isBefore(now, 'day')) {
      return 'overdue';
    } else if (deadlineDate.isSame(now, 'day')) {
      return 'today';
    } else {
      return 'upcoming';
    }
  }
  
  _getDeadlineMessage(deadline) {
    const status = this._getDeadlineStatus(deadline);
    switch (status) {
      case 'overdue':
        return '已逾期';
      case 'today':
        return '今天截止';
      case 'upcoming':
        const days = dayjs(deadline).diff(dayjs(), 'day');
        return `剩余${days}天`;
      default:
        return '';
    }
  }
  
  _getStatusText(status) {
    const statusMap = {
      0: '待立项',
      1: '已立项',
      2: '设计中',
      3: '开发中',
      4: '测试中',
      5: '已完成',
      99: '已取消'
    };
    return statusMap[status] || '未知状态';
  }
  
  _getStatusColor(status) {
    const colorMap = {
      0: '#9e9e9e', // 待立项 - 灰色
      1: '#2196f3', // 已立项 - 蓝色
      2: '#ff9800', // 设计中 - 橙色
      3: '#4caf50', // 开发中 - 绿色
      4: '#9c27b0', // 测试中 - 紫色
      5: '#4cd964', // 已完成 - 绿色
      99: '#f44336' // 已取消 - 红色
    };
    return colorMap[status] || '#9e9e9e';
  }
  
  _getProgressColor(percentage) {
    if (percentage >= 80) return '#4cd964'; // 绿色
    if (percentage >= 50) return '#ff9800'; // 橙色
    return '#2196f3'; // 蓝色
  }
  
  // 清理方法
  @action
  reset() {
    this.projects = [];
    this.quickAccessList = [];
    this.loading = false;
    this.filter = {
      search: '',
      status: 'all',
      cate: 0,
      devManager: 0,
      bizManager: 0,
      sortType: 'time'
    };
    this.pagination = {
      page: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    };
  }
}

export default new ProjectListStore(); 